import { useEffect, useRef } from "react";
import { history, Location } from "umi";

/**
 * 每次进入页面触发激活
 *
 * api说明
 * fn: (location: Location) => void
 * hook只支持传入一个函数，并且会返回一个当前路由的Location类型的路由对象
 */
const useActive = (fn: (location: Location) => void) => {
  // 当前页面hash
  const currHash = useRef<string>();

  useEffect(() => {
    const unlisten = history.listen((location: Location) => {
      if(window.location.hash.includes(location.pathname)) {
        if(!currHash.current || currHash.current === window.location.hash) {
          if(!currHash.current) currHash.current = window.location.hash;
          fn(location);
        }
      }
    });
    return () => unlisten?.();
  }, []);
};

export default useActive;
